package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.mapper.DestinationMapper;
import cn.wolfcode.luowowo.article.query.DestinationQueryObject;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class DestinationServiceImpl implements IDestinationService {

    @Autowired
    private DestinationMapper destinationMapper;

    @Override
    public List<Destination> getDestByDeep(Integer deep) {

        return destinationMapper.getDestByDeep(deep);
    }

    @Override
    public PageInfo queryForPageInfo(DestinationQueryObject qo) {

        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());

        return new PageInfo(destinationMapper.queryForList(qo));
    }

    @Override
    public void changeHotValue(int hot, Long id) {

        if (id != null) {
            destinationMapper.changeHotValue(hot, id);
        }

    }

    @Override
    public void delete(Long id) {

        if (id != null) {
            destinationMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public void setInfo(Long id, String info) {

        if (id != null) {

            destinationMapper.setInfo(id, info);
        }

    }


    @Override
    public List<Destination> getToasts(Long parentId) {

        List<Destination> toasts = new ArrayList<Destination>();

        if (parentId != null) {

            toasts = createToasts(parentId, toasts);
        }

        Collections.reverse(toasts);

        return toasts;
    }

    @Override
    public Destination selectById(Long id) {

        return destinationMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Destination> list() {

        return destinationMapper.selectAll();
    }


    public  List<Destination> createToasts(Long parentId, List<Destination> toasts) {

        if (parentId != null) {

            Destination destination = destinationMapper.selectByPrimaryKey(parentId);

            toasts.add(destination);

            if (destination.getParent() != null) {

                createToasts(destination.getParent().getId(), toasts);

            }

        }
        return toasts;

    }

}
